<?php

//定义项目名称和路径
define('APP_NAME', 'Zhitongche');
define('APP_PATH', '../Application/');
date_default_timezone_set('Asia/Shanghai');

//set time limit
set_time_limit(600);

//is ajax for nginx
if(!function_exists( 'fastcgi_finish_request' ))
{
	function fastcgi_finish_request()
	{
		set_time_limit(60);
	}
}

//设置全局的错误处理函数
function nz_exception($e)
{
	$exception_class = get_class($e);
	switch($exception_class){
		case 'OauthException':
			$resInfo = json_decode($e->getMessage(), true);
			$oauth_error = $resInfo['error'];
			$oauth_error_description = $resInfo['error_description'];
			include APP_PATH.'Tpl/Oauth_Error.html';
			exit(1);
			break;
		//内部错误
		case 'NewzanException':
		//API错误
		case 'TopClientException' :
			$code = $e->getCode();
			switch($code){
				case RetStatus::NOT_SERVER:
					include APP_PATH.'Tpl/NO_SERVER.html';
					break;

				//无权限访问
				case RetStatus::ACCESS_DENY:
					if( IS_AJAX ){
						$res = array(
								'status' => $code,
								'data' => array( 'msg' => $e->getMessage() )
						);
						echo json_encode($res);
					}else{
						redirect('/versions');
					}
					break;
			
				//需要登录
				case RetStatus::AUTH_REQUIRED:
					if( IS_AJAX ){
						$res = array(
								'status' => $code,
								'data' => array( 'msg' => $e->getMessage() )
						);
						echo json_encode($res);
					}else{
						redirect('/login');
					}
					break;
					
				//系统内部外部错误,用户输入参数错误
				case RetStatus::INNER_ERR:
				case RetStatus::INTER_ERR:
				case RetStatus::PARAM_ERR:
				default:
					Log::write($e->getMessage());
					Log::write($e->getTraceAsString());
					$msg = $e->getMessage();
					//处理一下特殊的没有开通直通车问题
					
					/** @var 修改此msg的时候一定要记得修改 Tpl/init.html下对应的msg 
					 *  @todo 改进为常量语言配置文件来统一定义这些输出
					 * */
					$no_shop_error_msg  = "您尚未开店或者没有开通直通车服务，无法使用本服务";
					$top_msg = getTopError($msg);
					if(getTopError($msg) == '无法根据nick获取直通车帐号信息') {
						if( IS_AJAX ) {
							$res = array(
								'status' => $code,
								'data' => array('msg' => $no_shop_error_msg)
							);
							echo json_encode($res);
						} else {
							halt($no_shop_error_msg);
						}						
					} else {
						if( IS_AJAX ) {
							$res = array(
									'status' => $code,
									'data' => array( 'msg' => $top_msg )
							);
							echo json_encode($res);
						} else {
							halt($top_msg);
						}
					}
					break;
			}
			break;
		default :
			Log::write($e->getMessage());
			Log::write($e->getTraceAsString());
			halt($e->getMessage());
			break;
	}
}

require("../ThinkPHP/ThinkPHP.php");
?>
